package com.example.xcpeekaboo.commands;

import com.example.xcpeekaboo.game.DisguiseManager;
import com.example.xcpeekaboo.game.GameManager;
import me.libraryaddict.disguise.disguisetypes.DisguiseType;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class GameCommands implements CommandExecutor, TabCompleter {
    private final GameManager gameManager;
    private final DisguiseManager disguiseManager;

    public GameCommands() {
        this.gameManager = GameManager.getInstance();
        this.disguiseManager = DisguiseManager.getInstance();
    }

    @Override
    public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
        if (!(sender instanceof Player)) {
            return new ArrayList<>();
        }

        Player player = (Player) sender;

        if (args.length == 1) {
            List<String> completions = new ArrayList<>();
            completions.add("join");
            completions.add("quit");
            completions.add("list");
            completions.add("help");
            
            if (player.hasPermission("xcpeekaboo.admin")) {
                completions.add("start");
                completions.add("setseeker");
                completions.add("sethider");
                completions.add("setspawn");
            }
            
            if (gameManager.isHider(player)) {
                completions.add("disguise");
            }
            
            return completions.stream()
                    .filter(s -> s.toLowerCase().startsWith(args[0].toLowerCase()))
                    .collect(Collectors.toList());
        }

        if (args.length == 2 && args[0].toLowerCase().equals("disguise") && gameManager.isHider(player)) {
            return Stream.of(DisguiseType.values())
                    .map(Enum::name)
                    .filter(s -> s.toLowerCase().startsWith(args[1].toLowerCase()))
                    .collect(Collectors.toList());
        }

        return new ArrayList<>();
    }

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        if (!(sender instanceof Player)) {
            sender.sendMessage("§c只有玩家才能使用此命令！");
            return true;
        }

        Player player = (Player) sender;

        if (!command.getName().equalsIgnoreCase("xcpkb")) {
            return false;
        }

        if (args.length < 1) {
            player.sendMessage("§c请使用 /xcpkb <join|start|quit|disguise|setspawn|list> 来使用命令！");
            return true;
        }

        String subCommand = args[0].toLowerCase();
        String[] subArgs = new String[args.length - 1];
        System.arraycopy(args, 1, subArgs, 0, args.length - 1);

        switch (subCommand) {
            case "start":
                return handleStart(player);
            case "join":
                return handleJoin(player);
            case "quit":
                return handleQuit(player);
            case "disguise":
                return handleDisguise(player, subArgs);
            case "setseeker":
                return handleSetSeeker(player);
            case "sethider":
                return handleSetHider(player);
            case "list":
                return handleList(player);
            case "help":
                return handleHelp(player);
            case "setspawn":
                return handleSetSpawn(player);
            default:
                player.sendMessage("§c未知的子命令！请使用 /xcpkb help 查看帮助");
                return true;
        }
    }

    private boolean handleHelp(Player player) {
        player.sendMessage("§e==========躲猫猫插件指令帮助===========");
        player.sendMessage("§6/xcpkb help §f- 显示此帮助信息");
        player.sendMessage("§6/xcpkb join §f- 加入游戏（将自动分配角色）");
        player.sendMessage("§6/xcpkb quit §f- 退出游戏");
        player.sendMessage("§6/xcpkb disguise [类型] §f- 查看或更改当前伪装（仅限躲藏者）");
        player.sendMessage("§6/xcpkb list §f- 显示当前游戏中的玩家列表");
        if (player.hasPermission("xcpeekaboo.admin")) {
            player.sendMessage("§6/xcpkb setseeker §f- 设置寻找者释放位置（需要管理员权限）");
            player.sendMessage("§6/xcpkb sethider §f- 设置躲藏者释放位置（需要管理员权限）");
            player.sendMessage("§6/xcpkb start §f- 开始游戏（需要至少一名寻找者和一名躲藏者）");
        }
        player.sendMessage("§e===================================");
        return true;
    }

    private boolean handleList(Player player) {
        player.sendMessage("§e当前游戏玩家列表：");
        
        // 显示寻找者列表
        player.sendMessage("§c寻找者：");
        if (gameManager.getSeekers().isEmpty()) {
            player.sendMessage("  §7暂无寻找者");
        } else {
            for (Player seeker : gameManager.getSeekers()) {
                player.sendMessage("  §c- " + seeker.getName());
            }
        }
        
        // 显示躲藏者列表
        player.sendMessage("§a躲藏者：");
        if (gameManager.getHiders().isEmpty()) {
            player.sendMessage("  §7暂无躲藏者");
        } else {
            for (Player hider : gameManager.getHiders()) {
                DisguiseType disguiseType = disguiseManager.getCurrentDisguise(hider);
                String disguiseInfo = disguiseType != null ? " (伪装: " + disguiseType.name() + ")" : " (无伪装)";
                player.sendMessage("  §a- " + hider.getName() + "§7" + disguiseInfo);
            }
        }
        return true;
    }

    private boolean handleStart(Player player) {
        if (!player.hasPermission("xcpeekaboo.admin")) {
            player.sendMessage("§c你没有权限启动游戏！");
            return true;
        }

        if (!gameManager.isGameRunning()) {
            if (gameManager.getSeekers().isEmpty() || gameManager.getHiders().isEmpty()) {
                player.sendMessage("§c无法开始游戏：需要至少一名寻找者和一名躲藏者！");
                return true;
            }
            gameManager.setGameRunning(true);
            player.getServer().broadcastMessage("§a躲猫猫游戏开始了！寻找者将在30秒后被释放！");
        } else {
            player.sendMessage("§c游戏已经在进行中！");
        }
        return true;
    }

    private boolean handleJoin(Player player) {
        if (gameManager.isGameRunning()) {
            player.sendMessage("§c游戏已经开始，无法加入！");
            return true;
        }

        if (gameManager.isSeeker(player) || gameManager.isHider(player)) {
            player.sendMessage("§c你已经在游戏中了！");
            return true;
        }

        // 计算当前寻找者和躲藏者的比例
        int seekerCount = gameManager.getSeekers().size();
        int hiderCount = gameManager.getHiders().size();
        
        // 如果寻找者数量为0，或者当前比例超过1:3，分配为寻找者
        if (seekerCount == 0 || (seekerCount * 3 < hiderCount)) {
            gameManager.addSeeker(player);
            player.sendMessage("§a你已被自动分配为寻找者队伍！");
        } else {
            gameManager.addHider(player);
            player.sendMessage("§a你已被自动分配为躲藏者队伍！");
        }
        
        // 传送玩家到游戏出生点
        if (gameManager.getGameSpawnLocation() != null) {
            player.teleport(gameManager.getGameSpawnLocation());
        }
        
        // 开始循环显示等待提示
        gameManager.startWaitingTask(player);
        return true;
    }

    private boolean handleQuit(Player player) {
        if (!gameManager.isSeeker(player) && !gameManager.isHider(player)) {
            player.sendMessage("§c你不在游戏中！");
            return true;
        }

        gameManager.cancelWaitingTask(player);

        if (gameManager.isSeeker(player)) {
            gameManager.removeSeeker(player);
        } else {
            gameManager.removeHider(player);
            disguiseManager.removeDisguise(player);
        }

        player.sendMessage("§a你已退出游戏！");
        return true;
    }

    private boolean handleDisguise(Player player, String[] args) {
        if (!gameManager.isHider(player)) {
            player.sendMessage("§c只有躲藏者才能使用此命令！");
            return true;
        }

        if (args.length < 1) {
            DisguiseType currentDisguise = disguiseManager.getCurrentDisguise(player);
            if (currentDisguise != null) {
                player.sendMessage("§a你当前的伪装是：" + currentDisguise.name());
            } else {
                player.sendMessage("§c你当前没有伪装！");
            }
            return true;
        }

        String disguiseType = args[0].toUpperCase();
        try {
            DisguiseType type = DisguiseType.valueOf(disguiseType);
            disguiseManager.disguisePlayer(player, type);
            player.sendMessage("§a伪装已更改为：" + type.name());
        } catch (IllegalArgumentException e) {
            player.sendMessage("§c无效的伪装类型！");
        }
        return true;
    }

    private boolean handleSetSeeker(Player player) {
        if (!player.hasPermission("xcpeekaboo.admin")) {
            player.sendMessage("§c你没有权限设置出生点！");
            return true;
        }

        gameManager.setSeekerSpawnLocation(player.getLocation());
        player.sendMessage("§a已设置寻找者释放位置！");
        return true;
    }

    private boolean handleSetHider(Player player) {
        if (!player.hasPermission("xcpeekaboo.admin")) {
            player.sendMessage("§c你没有权限设置出生点！");
            return true;
        }

        gameManager.setHiderSpawnLocation(player.getLocation());
        player.sendMessage("§a已设置躲藏者释放位置！");
        return true;
    }

    private boolean handleSetSpawn(Player player) {
        if (!player.hasPermission("xcpeekaboo.admin")) {
            player.sendMessage("§c你没有权限设置出生点！");
            return true;
        }

        gameManager.setGameSpawnLocation(player.getLocation());
        player.sendMessage("§a已设置游戏出生点！");
        return true;
    }
}